package com.devicemantra.coordinate.app;

import java.util.Date;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.devicemantra.coordinate.dao.Blog;
import com.devicemantra.coordinate.dao.Course;
import com.devicemantra.coordinate.dao.EmpAddress;
import com.devicemantra.coordinate.dao.HibernateUtil;
import com.devicemantra.coordinate.dao.TestPlan;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction {

	private String message;
	private String username;

	static final Logger logger = Logger.getLogger(LoginAction.class);

	public LoginAction() {
	}

	public String execute() {
		logger.info("*********************");
		setMessage("Hello " + getUsername());

		final Blog blog = new Blog();
		final Course course = new Course();
		final TestPlan testplan = new TestPlan();
		testplan.setName(username);
		testplan.setDate(new Date());

		course.setCourseId(123);
		course.setCourseName("C programming - Amith	");
		blog.setSubject(getUsername());
		blog.setBody("This is the body of my blog post");
		blog.setCreatedAt(new java.util.Date());

		final EmpAddress empAddress = new EmpAddress();
		empAddress.setEmp_name("NMPT Colony");
		empAddress.setEmp_phone("+61424955306");

		Transaction transaction = null;
		try {
			final Session session = HibernateUtil.getSession();
			transaction = session.beginTransaction();
			session.save(blog);
			session.save(empAddress);
			session.save(course);
			session.save(testplan);
			transaction.commit();
		} catch (final HibernateException e) {
			System.out.println("Rolling back");
			transaction.rollback();
			e.printStackTrace();
		}
		return ActionSupport.SUCCESS;
	}

	public static void main(final String[] args) {
		final Blog blog = new Blog();
		final Course course = new Course();
		course.setCourseId(123);
		course.setCourseName("C programming - Amith	");
		blog.setSubject("My test post");
		blog.setBody("This is the body of my blog post - Amith");
		blog.setCreatedAt(new java.util.Date());

		final Session session = HibernateUtil.getSession();

		final Transaction transaction = session.beginTransaction();

		session.save(blog);
		session.save(course);

		transaction.commit();
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(final String message) {
		this.message = message;
	}

	/**
	 * @return the userName
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param userName
	 *            the userName to set
	 */
	public void setUsername(final String userName) {
		logger.info("Set username called now");
		this.username = userName;
		logger.info("Set username called now " + username);
	}

}
